<template>
    <div class="conversation-management">
        <h2>会话信息管理</h2>
        <div class="conversation-content">
            <div class="session-selector" v-if="sessions.length > 0">
                <a-select 
                    v-model:value="selectedSessionId" 
                    style="width: 100%" 
                    @change="loadSessionMessages"
                    placeholder="请选择会话">
                    <a-select-option 
                        v-for="session in sessions" 
                        :key="session.id" 
                        :value="session.id">
                        {{ session.title || getSessionTitle(session) }}
                    </a-select-option>
                </a-select>
            </div>
            
            <div class="messages-list" v-if="selectedSessionId">
                <div 
                    v-for="(message, index) in currentMessages" 
                    :key="index" 
                    :class="['message-item', message.role]"
                >
                    <div class="message-header">
                        <span class="role">{{ message.role === 'user' ? '我' : 'AI助手' }}</span>
                        <span class="actions">
                            <a-popconfirm
                                title="确定要删除这条消息吗？"
                                @confirm="deleteMessage(index)"
                                ok-text="确定"
                                cancel-text="取消"
                            >
                                <a-button type="link" size="small" danger>删除</a-button>
                            </a-popconfirm>
                        </span>
                    </div>
                    <div class="message-content">
                        <div v-if="message.role === 'user'" class="user-message">
                            {{ message.content }}
                        </div>
                        <div v-else class="assistant-message" v-html="renderMarkdown(message.content)"></div>
                    </div>
                </div>
            </div>
            
            <div v-else class="empty-state">
                <p>请选择一个会话查看消息</p>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onActivated } from "vue";
import MarkdownIt from "markdown-it";

// 初始化Markdown解析器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
});

interface Message {
  role: "user" | "assistant" | "system";
  content: string;
}

interface Session {
  id: string;
  title: string;
  messages: Message[];
  lastUpdated: number;
  description?: string;
}

const sessions = ref<Session[]>([]);
const selectedSessionId = ref<string>("");
const currentMessages = ref<Message[]>([]);

// 获取会话标题
const getSessionTitle = (session: Session) => {
  if (session.title) return session.title;

  // 如果没有标题，从第一条消息生成标题
  if (session.messages.length > 0) {
    const firstUserMessage = session.messages.find(msg => msg.role === 'user');
    if (firstUserMessage) {
      // 取消息前15个字符作为标题
      return firstUserMessage.content.substring(0, 15) + (firstUserMessage.content.length > 15 ? '...' : '');
    }
  }

  return '新会话';
};

// 渲染Markdown内容
const renderMarkdown = (content: string) => {
  if (!content) return '';
  return md.render(content);
};

// 获取所有会话
const loadSessions = async () => {
  try {
    const response = await fetch('http://localhost:32068/api/sessions');
    const result = await response.json();
    
    if (result.data && Array.isArray(result.data)) {
      sessions.value = result.data;
    } else {
      sessions.value = [];
    }
  } catch (error) {
    console.error("获取会话列表失败:", error);
  }
};

// 加载选中会话的消息
const loadSessionMessages = (sessionId: string) => {
  const session = sessions.value.find(s => s.id === sessionId);
  if (session) {
    currentMessages.value = [...session.messages];
  }
};

// 删除消息
const deleteMessage = async (index: number) => {
  // 从当前消息列表中删除
  currentMessages.value.splice(index, 1);
  
  // 更新会话数据
  const sessionIndex = sessions.value.findIndex(s => s.id === selectedSessionId.value);
  if (sessionIndex !== -1) {
    // 更新会话中的消息
    sessions.value[sessionIndex].messages = [...currentMessages.value];
    
    // 更新会话的最后更新时间
    sessions.value[sessionIndex].lastUpdated = Date.now();
    
    // 保存到后端
    try {
      const sessionToUpdate = {
        ...sessions.value[sessionIndex],
        // 确保只传递必要的字段
        id: sessions.value[sessionIndex].id,
        title: sessions.value[sessionIndex].title,
        messages: sessions.value[sessionIndex].messages.map(msg => ({
          role: msg.role,
          content: msg.content
        })),
        lastUpdated: sessions.value[sessionIndex].lastUpdated,
        description: sessions.value[sessionIndex].description
      };
      
      const response = await fetch(`http://localhost:32068/api/sessions/${sessionToUpdate.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(sessionToUpdate),
      });
      
      const result = await response.json();
      if (result.code !== 200) {
        // 如果更新失败，恢复删除前的状态
        currentMessages.value.splice(index, 0, sessions.value[sessionIndex].messages[index]);
        sessions.value[sessionIndex].messages = [...currentMessages.value];
        throw new Error(result.error || "更新会话失败");
      }
      
      console.log("消息删除成功");
    } catch (error) {
      console.error("删除消息失败:", error);
      // 显示错误提示
      alert("删除消息失败: " + (error as Error).message);
    }
  }
};

onMounted(async () => {
  await loadSessions();
});
onActivated(() => {
  loadSessions();
});
</script>

<style scoped>
.conversation-management {
    padding: 20px;
    height: 100%;
    overflow: hidden;
}

.conversation-management h2 {
    margin-bottom: 20px;
}

.conversation-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
    height: calc(100% - 40px);
}

.session-selector {
    flex: 0 0 auto;
}

.messages-list {
    flex: 1;
    overflow-y: auto;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    padding: 10px;
}

.message-item {
    padding: 10px;
    border-bottom: 1px solid #f0f0f0;
}

.message-item:last-child {
    border-bottom: none;
}

.message-item.user {
    background-color: #f0f8ff;
}

.message-item.assistant {
    background-color: #fff;
}

.message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
}

.role {
    font-weight: bold;
    font-size: 14px;
}

.user-message {
    white-space: pre-wrap;
    line-height: 1.5;
}

.assistant-message {
    line-height: 1.5;
}

.assistant-message :deep(p) {
    margin: 0 0 10px 0;
}

.assistant-message :deep(ul),
.assistant-message :deep(ol) {
    margin: 10px 0;
    padding-left: 20px;
}

.assistant-message :deep(li) {
    margin-bottom: 5px;
}

.assistant-message :deep(pre) {
    background-color: #f5f5f5;
    padding: 10px;
    border-radius: 4px;
    overflow-x: auto;
}

.assistant-message :deep(code) {
    font-family: monospace;
}

.empty-state {
    text-align: center;
    padding: 40px 0;
    color: #999;
}
</style>